package org.example.sys.ui.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.example.sys.App
import org.example.sys.SingleLiveEvent
import org.example.sys.service.BookApi
import org.example.sys.bean.Book
import org.example.sys.bean.BookItem
import org.example.sys.bean.ResponseData
import org.example.sys.bean.TableData
import java.lang.Exception


open class HomeViewModel : ViewModel() {

    private val bookIndex = hashMapOf<Int, Book>()
    val loadStateLiveData = SingleLiveEvent<State>()
    val bookLiveData = SingleLiveEvent<MutableList<Book>>()
    val idLiveData = SingleLiveEvent<BookItem>()
    var pageSize = 10
    var currentPage = 0

    fun start() {
        currentPage = 0
        getBooks(0, pageSize)
    }

    fun get(currentTotal: Int) {
        currentPage = currentTotal / pageSize
        currentPage++
        getBooks(currentPage, pageSize)
    }

    private fun getBooks(pageNo: Int, pageSize: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var responseData: ResponseData<TableData<Book>>? = null
                loadStateLiveData.postValue(State.Loading)
                responseData = App.bookApi.get(pageNo, pageSize).execute().body()
                responseData?.apply {
                    if (code == 0 && data != null) {
                        if (currentPage == 0) {
                            bookIndex.clear()
                            loadStateLiveData.postValue(State.Clear)
                        }
                        val bookList = mutableListOf<Book>()
                        data.tableData.forEach {
                            if (!bookIndex.containsKey(it.id)) {
                                bookIndex.put(it.id, it)
                                bookList.add(it)
                            }
                        }
                        bookLiveData.postValue(bookList)
                    }
                }
            } catch (e: Exception) {
                loadStateLiveData.postValue(State.Error)
            }
            loadStateLiveData.postValue(State.NotLoading)
        }
    }

    fun deleteBook(item: BookItem) {
        var responseData: ResponseData<Book>? = null
        viewModelScope.launch(Dispatchers.IO) {
            val id = item.item.id
            responseData = App.bookApi.delete(id).execute().body()
            responseData?.apply {
                if (code == 0) {
                    bookIndex.remove(id)
                    idLiveData.postValue(item)
                }
            }
        }
    }

    enum class State {
        Loading, Clear, Error, NotLoading
    }
}